using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace SCADAEditor
{
    /// <summary>
    /// 属性网格绑定器，用于将对象属性绑定到PropertyGrid控件
    /// </summary>
    public class PropertyGridBinder
    {
        /*
        // 初始化
        var binder = new PropertyGridBinder(myPropertyGrid);

        // 绑定对象
        binder.Bind(myObject);

        // 清除绑定
        binder.Clear();
        */
        private PropertyGrid _propertyGrid;

        public PropertyGridBinder(PropertyGrid propertyGrid)
        {
            _propertyGrid = propertyGrid ?? throw new ArgumentNullException(nameof(propertyGrid));
        }

        /// <summary>
        /// 绑定对象到PropertyGrid
        /// </summary>
        /// <param name="target">要绑定的对象</param>
        public void Bind(object target)
        {
            if (target == null)
            {
                _propertyGrid.SelectedObject = null;
                return;
            }

            // 处理自定义类型
            // if (!IsSimpleType(target.GetType()))
            // {
            //     // 为自定义类型添加TypeConverter支持
            //     TypeDescriptor.AddAttributes(target.GetType(), 
            //         new TypeConverterAttribute(typeof(ExpandableObjectConverter)));
            // }

            _propertyGrid.SelectedObject = target;
        }

        /// <summary>
        /// 判断是否为简单类型
        /// </summary>
        private bool IsSimpleType(Type type)
        {
            return type.IsPrimitive || 
                   type.IsEnum || 
                   type == typeof(string) || 
                   type == typeof(decimal) ||
                   Nullable.GetUnderlyingType(type) != null;
        }

        /// <summary>
        /// 清除绑定
        /// </summary>
        public void Clear()
        {
            _propertyGrid.SelectedObject = null;
        }
    }
}